package com.wy.utils;

import java.io.*;
import java.nio.charset.Charset;

public class window {
    public static void main(String[] args) {
        try {
            // 保存日志的文件路径
            String outputFilePath = "C:\\Users\\wy\\Desktop\\黑屏\\event_log_output.txt";

            // PowerShell 命令：提取过去 1 小时的关键日志
            String command = "powershell -Command \"chcp 936; Get-WinEvent -FilterHashtable @{LogName='System'; Level=1,2,3} "
                    + "| Where-Object {$_.TimeCreated -ge (Get-Date).AddHours(-2)} "
                    + "| Format-Table TimeCreated, Id, LevelDisplayName, Message -AutoSize\"";

            // 执行命令
            Process process = Runtime.getRuntime().exec(command);

            // 使用 GBK 编码读取输出
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), Charset.forName("GBK"))
            );

            // 写入文件
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outputFilePath), Charset.forName("UTF-8")
            ));

            String line;
            System.out.println("正在提取日志并保存到文件：" + outputFilePath);
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }

            // 关闭流
            writer.close();
            reader.close();

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("日志提取完成！请查看文件：" + outputFilePath);
            } else {
                System.err.println("命令执行失败，退出代码：" + exitCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
